﻿using AutoMapper;
using BaseData.API.Read.Applications.Commands;
using BaseData.API.Read.Dtos;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MediatR;

namespace BaseData.API.Read.Applications.CommandHandlers
{
    /// <summary>
    /// 权限管理查询命令
    /// </summary>
    public class PermissionQueryCommandHandler : IRequestHandler<PermissionQueryCommand, ApiResult<ApiPaging<PermissionDTO>>>
    {
        private readonly IBaseRepository<Permission> perRep;
        private readonly IMapper mapper;

        public PermissionQueryCommandHandler(IBaseRepository<Permission> perRep,IMapper mapper)
        {
            this.perRep = perRep;
            this.mapper = mapper;
        }
        public Task<ApiResult<ApiPaging<PermissionDTO>>> Handle(PermissionQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<PermissionDTO>>result = new ApiResult<ApiPaging<PermissionDTO>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            var list = perRep.GetAll().Where(x => !x.IsDel);
            if(!string.IsNullOrEmpty(request.PermissionName))
            {
                list = list.Where(x => x.PermissionName.Contains(request.PermissionName));
            }
            //分页
            int TotalCount = list.Count();
            int PageCount = (int)Math.Ceiling((double)TotalCount / request.PageSize);

            list = list.OrderBy(x => x.PermissionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            ApiPaging<PermissionDTO> paging = new ApiPaging<PermissionDTO>();
            paging.TotalCount = TotalCount;
            paging.PageCount = PageCount;
            paging.Data = mapper.Map<List<PermissionDTO>>(list.ToList());

            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
